package com.demo.webapp.search.interceptor;

import java.lang.reflect.Method;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor;
import com.opensymphony.xwork2.interceptor.ValidationWorkflowAware;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * 可选择的Workflow拦截器 主要处理
 * {@link com.opensymphony.xwork2.interceptor.annotations.InputConfig}中
 * methodName与resultName不能同时出现的问题。 <br>
 * 处理结果:
 * <p>当methodName与resultName同时出现时,methodName将首先执行后,返回resultName方法</p>
 * 
 * @author ryuu.kk
 * 
 */
public class ChosenWorkflowInterceptor extends DefaultWorkflowInterceptor {

	/**
	 * 版本
	 */
	private static final long serialVersionUID = -6885453181132443616L;

	private static final Logger LOG = LoggerFactory.getLogger(ChosenWorkflowInterceptor.class);
	
	//
    private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];
    
    private String inputResultName = Action.INPUT;

    //@see com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor#setInputResultName
    public void setInputResultName(String inputResultName) {
        this.inputResultName = inputResultName;
    }
    
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		Object action = invocation.getAction();

		if (action instanceof ValidationAware) {
			ValidationAware validationAwareAction = (ValidationAware) action;

			if (validationAwareAction.hasErrors()) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Errors on action " + validationAwareAction
							+ ", returning result name 'input'");
				}

				String resultName = inputResultName;

				if (action instanceof ValidationWorkflowAware) {
					resultName = ((ValidationWorkflowAware) action)
							.getInputResultName();
				}

				InputConfig annotation = action.getClass().getMethod(invocation.getProxy().getMethod(), EMPTY_CLASS_ARRAY).getAnnotation(InputConfig.class);
				if (annotation != null) {
					if (!annotation.methodName().equals("")) {
						Method method = action.getClass().getMethod(annotation.methodName());
						resultName = (String) method.invoke(action);
						//对resultName进行判断
						if (annotation.resultName()!= null && annotation.resultName().trim().length() > 0 ) {
							resultName = annotation.resultName();
						}
					} else {
						resultName = annotation.resultName();
					}
				}
				return resultName;
			}
		}
		return invocation.invoke();
	}
}
